package com.woniuxy.ai.controller;

import com.woniuxy.ai.callback.StreamProcessor;
import com.woniuxy.ai.service.AIChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@CrossOrigin
public class AIChatController {

    @Autowired
    private AIChatService aiChatService;

    private final ExecutorService executor = Executors.newCachedThreadPool();

    // 流式聊天(返回SSE流式数据，一个个词返回)
    @GetMapping("/chat-stream")
    public SseEmitter chatStream(@RequestParam String input,
                                 @RequestParam(required = false) String sessionId) { // 新增sessionId参数

        // 生成新会话ID（如果未提供）
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = UUID.randomUUID().toString();
        }


        SseEmitter emitter = new SseEmitter(60 * 1000L); // 设置60秒超时

        String finalSessionId = sessionId;
        executor.execute(() -> {
            try {
                aiChatService.chatWithAIStream(input, finalSessionId, new StreamProcessor() {
                    @Override
                    public void onChunk(String content) {
                        try {
                            // 直接发送内容块，而不是逐个字符
                            emitter.send(SseEmitter.event()
                                    .data(content)
                                    .id(finalSessionId) // 设置sessionId作为事件ID
                                    .name("message"));
                        } catch (Exception e) {
                            emitter.completeWithError(e);
                        }
                    }

                    @Override
                    public void onComplete() {
                        emitter.complete();
                    }

                    @Override
                    public void onError(Throwable t) {
                        emitter.completeWithError(t);
                    }
                });
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    // 普通聊天(一个json返回所有文字)
    @PostMapping("/chat")
    public String chat(@RequestParam String input) throws Exception {
        return aiChatService.chatWithAI(input);
    }
    // 新增：生成随机社区小贴士的接口
    @GetMapping("/tip/random")
    public String getRandomCommunityTip() throws Exception {
        // 调用AI模型生成社区小贴士
        String prompt = "请生成一条实用的社区生活小贴士，" +
                "语言风格要亲切友好，" +
                "适合社区居民阅读，不需要写标题，只需要一句话，" +
                "字数在30字左右。";

        // 调用AI服务生成回复
        return aiChatService.chatWithAI(prompt);
    }
    @GetMapping("/analyze")
    public String analyzeData(@RequestParam String apiUrl) throws IOException {
        String rawData = aiChatService.fetchDataFromExternalAPI(apiUrl);
        return aiChatService.analyzeDataWithAI(rawData);
    }
}